﻿using Microsoft.Xna.Framework;
using PS.DataTypes;

namespace PS.Algorithms
{
    public class CollisionDetector
    {
        public static bool Intersects(Line line1, Line line2, out Vector2 intersection)
        {
            intersection = Vector2.Zero;
            bool intersects = false;

            float ua;
            float ub;
            float delta;

            LineLineIntersection(line1, line2, out delta, out ua, out ub);

            if (delta == 0f) // parallel
            {
                if (ua == 0f && ub == 0f) // coincident
                {
                    intersects = true;
                    intersection.X = line1.From.X;
                    intersection.Y = line1.From.Y;
                }
            }
            else
            {
                ua /= delta;
                ub /= delta;

                if (ua >= 0 && ua <= 1 && ub >= 0 && ub <= 1)
                {
                    intersects = true;
                    intersection.X = line1.From.X + ua * (line1.To.X - line1.From.X);
                    intersection.Y = line1.From.Y + ua * (line1.To.Y - line1.From.Y);
                }
            }

            return intersects;
        }

        public static bool Intersects(Line line1, Line line2)
        {
            Vector2 outParam = Vector2.Zero;
            return Intersects(line1, line2, out outParam);
        }

        // Line line intersection from Wikipedia http://en.wikipedia.org/wiki/Line-line_intersection
        private static Vector2 LineLineIntersection(Line line1, Line line2, out float delta, out float ua, out float ub)
        {
            Vector2 intersection = new Vector2();

            float x1 = line1.From.X;
            float y1 = line1.From.Y;
            float x2 = line1.To.X;
            float y2 = line1.To.Y;

            float x3 = line2.From.X;
            float y3 = line2.From.Y;
            float x4 = line2.To.X;
            float y4 = line2.To.Y;

            delta = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
            ua = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3);
            ub = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3);

            intersection.X = ua / delta;
            intersection.Y = ub / delta;

            return intersection;
        }
    }
}
